package com.cn.jx.manager.service.query.Impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import com.cn.jx.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cn.jx.common.util.page.PageObj;
import com.cn.jx.manager.dao.NoticeRepository;
import com.cn.jx.manager.po.Notice;
import com.cn.jx.manager.po.User;
import com.cn.jx.manager.service.query.INoticeServiceQry;
import com.cn.jx.manager.service.query.IUserServiceQry;

import com.jx.jpaQuery.QueryCondition;
import com.jx.util.ArrayUtil;
import com.jx.util.Constant;
import com.jx.util.DateUtil;
import com.jx.util.MapObject;

@Service("noticeServiceQry") 
@Transactional
public class NoticeServiceImplQry extends BaseService implements INoticeServiceQry {

	@Autowired
	private NoticeRepository noticeDao;
	@Autowired
	private IUserServiceQry userServiceQry;
	
	@Override
	@Transactional(readOnly = true)
	public PageObj<MapObject> findNoticePage(QueryCondition cond) throws Exception {
		Specification<Notice> speci = getSpecification(cond);
		Pageable pageable = getPageables(cond);
		Page<Notice> res = noticeDao.findAll(speci, pageable);
		List<Notice> rescontent=res.getContent();
		List<MapObject> listContent=new ArrayList<MapObject>();
		if(ArrayUtil.listNotEmpty(rescontent)){
			rescontent.forEach(r->{
				String auth="";
				if(Constant._SUPER.equals(r.getCreateUser())){
					auth="超级管理员";
				}else{
					User u=userServiceQry.getUserById(r.getCreateUser());
					if(u!=null){
						auth=u.getChineseName();
					}
				}
				MapObject mp=MapObject.getInstance();
				mp.put("title", r.getTitle());
				mp.put("subTitle",r.getSubTitle());
				mp.put("content", r.getContent());
				mp.put("createUser", auth);
				mp.put("createTime", DateUtil.getDateFmt(r.getCreateTime()));
				mp.put("id", r.getId());
				listContent.add(mp);
			});
		}
		PageObj<MapObject> pageRes = PageObj.of(res, listContent);
		return pageRes;
	}

	@Override
	@Transactional(readOnly = true)
	public Notice getNoticeById(String id) {
		Notice notice = findEntityByPkid(id, Notice.class);
		return notice;
	}

	@Override
	@Transactional(readOnly = true)
	public List<Notice> findLatestFive() {
		String sql="from Notice where delFlg=0 and validFlg=1 order by createTime desc ";
		Query query = entityManager.createQuery(sql, Notice.class);
		query.setFirstResult(0);
		query.setMaxResults(5);
		@SuppressWarnings("unchecked")
		List<Notice> puser = query.getResultList();
		return puser;
	}
}
